package com.lsc.shiro;

import com.lsc.Service.UserService;
import com.lsc.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;

import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: 自定义一个shiro中的Realm类
 * @description: 认证授权
 * @author: 上河图
 * @create: 2020-09-29 12:24
 */

public class userRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //    授权 AuthorizationInfo  principals用户信息封装
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //principals 从认证方法中获取到的，
        User currentUser = (User) principals.getPrimaryPrincipal();

        //得到数据库的认证字段或者认证表。  根据那个字段来授权的。
        info.addStringPermission(currentUser.getAuthor());

        //返回授权结果
        return info;
    }

//    认证 AuthenticationInfo

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //将controller层中的token拿来，然后和数据库的数据进行配对，
        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;

        //从数据库中查询数据
        User user = userService.query_User(usertoken.getUsername());

        //进行配对，如果在数据库中没有找到该用户的话，就会返回null的错误。
        if (null == user) {
            return null;  //null会在Controller层中报异常错误
        }

        //realname 域名
        //返回认证信息
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
